import { PdfJs, Spinner } from "../../core";

import AttachmentList from "./AttachmentList";
import FileItem from "./FileItem";
import { FC, useEffect, useState } from "react";

interface AttachmentLoaderProps {
  doc: PdfJs.PdfDocument;
}

interface AttachmentState {
  files: FileItem[];
  isLoaded: boolean;
}

const AttachmentLoader: FC<AttachmentLoaderProps> = ({ doc }) => {
  const [attachments, setAttachments] = useState<AttachmentState>({
    files: [],
    isLoaded: false,
  });

  useEffect(() => {
    doc.getAttachments().then((response) => {
      const files = response
        ? Object.keys(response).map((file) => {
            return {
              data: response[file].content,
              fileName: response[file].filename,
            };
          })
        : [];
      setAttachments({
        files,
        isLoaded: true,
      });
    });
  }, [doc]);

  return !attachments.isLoaded ? (
    <Spinner />
  ) : (
    <AttachmentList files={attachments.files} />
  );
};

export default AttachmentLoader;
